package practise.alogrithm.introductionToAlogrithm.dataStructures;


import practise.alogrithm.introductionToAlogrithm.ListNode;

/**
 * use a linked list to implement a queue.
 */
public class LinkedQueue<T> {
    ListNode<T> linkedList = new ListNode();
    ListNode<T> endNode = new ListNode() ;

    public void enqueue(T object){
        ListNode<T> element = new ListNode();
        element.setValue(object);
        if(endNode.getNext()!=null)
            endNode.getNext().setNext(element);
        endNode.setNext(element);
        if(linkedList.getValue()==null){
            linkedList=element;

        }

    }

    public T dequeue(){
        if(linkedList==null){
            throw new IndexOutOfBoundsException();
        }
        T element = linkedList.getValue();

        if(linkedList==endNode.getNext()){
            endNode.setNext(null);
        }
        linkedList = linkedList.getNext();
        return element;

    }


    public static void main(String[] args){
        LinkedQueue linkedQueue = new LinkedQueue();
        for(int i=0; i<7;i++){
            linkedQueue.enqueue(i);
        }

        for(int i=0;i<8;i++){
            System.out.print("["+linkedQueue.dequeue()+"]");
        }

    }

}
